package android.FiltrosJava;

import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;

public class PixelDistribution extends AbstractImageBasic{
    double RP = 0.2989;
    double GP = 0.5866;
    double BP = 1 - RP - GP;
    
	public BufferedImage applyFilter(BufferedImage dst) {
		BufferedImage src = copiaImagem(dst);
				
		int light;
		int[] L0, L1;
		int dimX = src.getWidth();
		int dimY = src.getHeight();
		WritableRaster raster_src = src.getRaster();
    	WritableRaster raster_dst = dst.getRaster();    	
    	int[] imageData = new int[raster_src.getNumBands()]; 
		
    	L1 = zeroVector(dimY);
    	for (int x = 0; x < dimX; x++){
    		L0 = L1;
    		L1 = zeroVector(dimY);
    		
    		for (int y = 0; y < dimY; y++){
    			raster_src.getPixel(x,y,imageData);
    			light = (int) (imageData[0] * RP + imageData[1] * GP + imageData[2] * BP);
    			light += L0[y];
    			
    			if (light > 255){
    				imageData[0] = 255;
    				imageData[1] = 255;
    				imageData[2] = 255;
    				light -= 255;    				    				
    			}else{
    				imageData[0] = 0;
    				imageData[1] = 0;
    				imageData[2] = 0;   				    				
    			}
    			    				
    			raster_dst.setPixel(x,y,imageData);
    			
    			L1[y] += (int) (light / 4);
    			if (y < (dimY-1)){
    				L0[y+1] += (int)(light / 4);
    				L1[y+1] += (int) (light - 3*(light / 4));
    			}
    			
    			if (y > 0)
    				L1[y-1] += (int) (light / 4);
    				
			}
		}
		src = null;
		return dst;		
    }
	
	public int[] zeroVector(int size){
		int []v = new int[size];
		
		for (int y= 0; y < size; y++){
			v[y] = 0;
		}
		
		return v;
	}
}
